package com.topvision.myviewtest.wificonnect;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.topvision.myviewtest.R;
import com.topvision.myviewtest.utils.DisplayUtil;
import com.topvision.myviewtest.wificonnect.wifi_1.WiFiConnectManager;

import java.util.List;

public class WifiTestActivity extends AppCompatActivity implements WiFiConnectManager.WiFiConnectListener {
    private final String TAG = getClass().getSimpleName();
    private ScrollView mScroll;
    private LinearLayout mTvGrounp;
    private WiFiConnectManager mConnectManager;
    private WifiReceiver mWifiReceiver;
    private WifiManager mWifiManager;
    private ConnectivityManager mConnectivityManager;
    private String curSSID;
    private String curPassWord;
    public static final int TIME = 10000;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    curSSID = "Topvision";
                    curPassWord = "TV69129712";
                    mHandler.sendEmptyMessageDelayed(1, TIME);
                    break;
                case 1:
                    curSSID = "TopVideo";
                    curPassWord = "TV69129712";
                    mHandler.sendEmptyMessageDelayed(2, TIME);
                    break;
                case 2:
                    curSSID = "中文名WIFI";
                    curPassWord = "123456789";
                    mHandler.sendEmptyMessageDelayed(3, TIME);
                    break;
                case 3:
                    curSSID = "Topvision-mifi";
                    curPassWord = "TV69129712";
                    mHandler.sendEmptyMessageDelayed(0, TIME);
                    break;
                default:
                    break;
            }
            addLine();
            addView("开始扫描WIFI");
            mWifiManager.startScan();
        }
    };
    private MyRunnable mRunnable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wifi_test);

        mRunnable = new MyRunnable();
        mScroll = (ScrollView) findViewById(R.id.id_scroll);
        mTvGrounp = (LinearLayout) findViewById(R.id.id_tv_grounp);
        mConnectManager = new WiFiConnectManager(this);
        mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        registerWifiReceiver();
        mHandler.sendEmptyMessageDelayed(0, TIME);
    }


    public void connect_topvision(View view) {
        curSSID = "Topvision";
        curPassWord = "TV69129712";
        addLine();
        addView("开始扫描WIFI");
        mWifiManager.startScan();
//        connect(curSSID, curPassWord);
    }

    public void connect_topvideo(View view) {
        curSSID = "TopVideo";
        curPassWord = "TV69129712";
        addLine();
        addView("开始扫描WIFI");
        mWifiManager.startScan();
//        connect(curSSID, curPassWord);
    }

    public void connect_ap(View view) {
        curSSID = "中文名WIFI";
        curPassWord = "123456789";
        addLine();
        addView("开始扫描WIFI");
        mWifiManager.startScan();
//        connect(curSSID, curPassWord);
    }

    public void connect_topvision_mifi(View view) {
        curSSID = "Topvision-mifi";
        curPassWord = "TV69129712";
        addLine();
        addView("开始扫描WIFI");
        mWifiManager.startScan();
//        connect(curSSID, curPassWord);
    }

    @Override
    public void connectStart() {
        addView("连接开始");
    }

    @Override
    public void connectResult(String ssid, boolean isSuccess) {
        addView(" 连接" + (isSuccess ? "成功->" : "失败->") + ssid);
    }

    @Override
    public void connectEnd() {
        addView("连接完成");
    }

    private void addView(String text) {
        TextView textView = new TextView(this);
        textView.setTextSize(DisplayUtil.sp2px(this, 18));
        textView.setText(text);
        mTvGrounp.addView(textView);
        mHandler.post(mRunnable);
    }

    private void addLine() {
        if (mTvGrounp.getChildCount() > 0) {
            addView("-------分割线-------");
        }
    }

    private void connect(String ssid, String password) {
        addLine();
        mConnectManager.connectWiFi(ssid, password, this);
    }

    public void clear(View view) {
        mTvGrounp.removeAllViews();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unRegisterWifiReceiver();
        mHandler.removeCallbacksAndMessages(null);
    }

    private void registerWifiReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        // 监听网络变化
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        mWifiReceiver = new WifiReceiver();
        registerReceiver(mWifiReceiver, intentFilter);
    }


    private void unRegisterWifiReceiver() {
        if (mWifiReceiver != null) {
            unregisterReceiver(mWifiReceiver);
        }
    }

    class WifiReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION) || action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                //连接状态改变
                addCurConnectWifi();
            }else if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
                //扫描完成
                connectWifi();
            }
        }
    }

    private void connectWifi() {
        addView("扫描完成");
        List<ScanResult> scanResults = mWifiManager.getScanResults();
        for (ScanResult scanResult : scanResults) {
            if (scanResult.SSID.equalsIgnoreCase(curSSID)) {
                addView("找到' " + curSSID + " ', 正在连接...");
                mConnectManager.connectWiFi(scanResult,curPassWord,this);
                return;
            }
        }
        addView("没有找到' " + curSSID + " '");
    }

    private void addCurConnectWifi() {
        NetworkInfo wifiNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (wifiNetworkInfo.isConnected()) {
            String ssid = getConnectWifiSSID();
            if (ssid != null) {
                addView("系统获取到的连接SSID:" + ssid);
            }
        }
    }

    public String getConnectWifiSSID() {
        WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
        if (wifiInfo != null) {
            return wifiInfo.getSSID();
        }
        return null;
    }

    class MyRunnable implements Runnable {
        @Override
        public void run() {
            mScroll.fullScroll(ScrollView.FOCUS_DOWN);
        }
    }
}
